<template>
  <div class="layout-padding">
    <splitpanes>
      <pane size="15">
        <div class="layout-padding-auto layout-padding-view">
          <el-scrollbar>
            <query-tree :placeholder="$t('common.queryDeptTip')" :query="deptData.queryList" :show-expand="true"
              @node-click="handleNodeClick" :handleKeyChange="keyChangeList">
              <!-- 没有数据权限提示 -->
              <template #default="{ node, data }">
                <el-tooltip v-if="data.isLock" class="item" effect="dark" :content="$t('sysuser.noDataScopeTip')"
                  placement="right-start">
                  <span>{{ node.label }}
                    <SvgIcon name="ele-Lock" />
                  </span>
                </el-tooltip>
                <span v-if="!data.isLock">{{ node.label }}</span>
              </template>
            </query-tree>
          </el-scrollbar>
        </div>
      </pane>
      <pane class="ml8">
        <div class="layout-padding-auto layout-padding-view">
          <el-row>
            <div class="mb8" style="width: 100%">
              <el-row v-show="showSearch">
                <el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList">
                  <el-form-item label="工号" prop="username">
                    <el-input v-model="state.queryForm.username" placeholder="请输入工号" clearable />
                  </el-form-item>
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="state.queryForm.name" placeholder="请输入姓名" clearable />
                  </el-form-item>
                  <el-form-item label="时间" prop="month">
                    <el-date-picker type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                      v-model="state.queryForm.month" placeholder="请选择时间">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="所属班次" label-width="100px" prop="classesId">
                    <el-select class="w100" clearable placeholder="请选择所属班组" v-model="state.queryForm.classesId"
                      @change="banCiSelect(state.queryForm.classesId)">
                      <el-option :key="item.id" :label="item.classesName" :value="item.id" v-for="item in banCiLists">
                        {{ item.classesName }}
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="所属班组" label-width="100px" prop="groupId">
                    <el-select class="w100" clearable placeholder="请选择所属班组" v-model="state.queryForm.groupId">
                      <el-option :key="item.id" :label="item.groupName" :value="item.id" v-for="item in banZuLists">
                        {{ item.groupName }}
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button icon="Search" type="primary" @click="getDataList">{{ $t('common.queryBtn') }}</el-button>
                    <el-button icon="Refresh" @click="resetQuery">{{ $t('common.resetBtn') }}</el-button>
                    <el-button icon="folder-add" type="primary" class="ml10" @click="selectionMoreChangDialog(userList)"
                      v-auth="'personnel_userClasses_add'">
                      排班
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-row>
            </div>
          </el-row>
          <el-table ref="multipleTableRef" :data="state.dataList" v-loading="state.loading" border
            :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle" @row-click="rowclick"
            @selection-change="selectionChangHandle" @sort-change="sortChangeHandle">
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="username" label="工号" width="110" />
            <el-table-column prop="name" label="姓名" width="110" />
            <el-table-column prop="classesName" label="当前班次" width="150">
              <template #default="scope">

                <div>{{ scope.row.classesName == null ? '未排班' : scope.row.classesName }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="groupName" label="当前班组" width="150">
              <template #default="scope">
                <div>{{ scope.row.groupName == null ? '未排班' : scope.row.groupName }}</div>
              </template>
            </el-table-column>


            <el-table-column
              v-if="state.dataList != null && state.dataList.length > 0 && state.dataList[0].details != null"
              v-for="item in state.dataList[0].details" :key="item" :label="item.day + ' ' + item.week" width="150">
              <template #default="scope">
                <div v-for="(item1, index1) in scope.row.details" :key="index1">

                  <div v-if="item.day == item1.day">
                    <div v-if="item1.works != null && item1.works.length > 0">
                      <div v-for="(item2, index2) in item1.works" :key="index2">
                        {{ item2.ruleName + ' - ' + item2.groupName }}
                      </div>
                    </div>
                    <div v-else>
                      休班
                    </div>
                  </div>

                </div>

              </template>
            </el-table-column>
            <el-table-column prop="effectTime" label="生效时间" width="150" />
            <!-- <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button icon="Search" text type="primary" v-auth="'personnel_userClasses_edit'"
                  @click="formDetailDialogRef.openDetailDialog(scope.row.username)">详情</el-button>
                <el-button icon="edit-pen" text type="primary" v-auth="'personnel_userClasses_edit'"
                  @click="selectionChangDialog(scope.row.id, state.queryForm.pkDept)">编辑</el-button>
              </template>
            </el-table-column> -->
          </el-table>
          <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
        </div>
      </pane>
    </splitpanes>





    <!-- 编辑、新增  -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />
    <form-more-dialog ref="formMoreDialogRef" @refresh="getDataList(false)" />
    <form-detail-dialog ref="formDetailDialogRef" @refresh="getDataList(false)" />

  </div>
</template>

<script setup lang="ts" name="systemUserClasses">
import { BasicTableProps, useTable } from "/@/hooks/table";
import { banCiList, banZuList, delObjs, deptTree, getUserList } from "/@/api/personnel/userClasses";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { useDict } from '/@/hooks/dict';
import { formatDate } from '/@/utils/formatTime';
// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const FormMoreDialog = defineAsyncComponent(() => import('./formMore.vue'));
const FormDetailDialog = defineAsyncComponent(() => import('./formDetail.vue'));

const QueryTree = defineAsyncComponent(() => import('/@/components/QueryTree/indexUser.vue'));
// 定义查询字典
let multipleTableRef = ref('')

// 定义变量内容
const formDialogRef = ref()
const formMoreDialogRef = ref()

const formDetailDialogRef = ref()
//部门list
const keyChangeList = ref([])
// 搜索变量
const queryRef = ref()
const showSearch = ref(true)
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
const userList = ref([])
const banCiLists = ref([])
const banZuLists = ref([])
// 部门树使用的数据
const deptData = reactive({
  queryList: (name: String) => {
    return deptTree({
      deptName: name,
    });
  },
});
onMounted(() => {

  getBanCiList()
})


//实现点击表格行勾选该行
const rowclick = (row: any) => {
  if (!row.disabled) {
    multipleTableRef.value.toggleRowSelection(row)
  }
}

const getBanCiList = () => {
  banCiList().then((res: any) => {
    banCiLists.value = res.data.records
    banCiLists.value.push({ id: 0, classesName: '未排班' })
  })
}

const banCiSelect = (e) => {
  state.queryForm.groupId = ''
  getBanZuList(e)
}

const getBanZuList = (e) => {
  banZuList({ classesId: e }).then((res: any) => {
    banZuLists.value = res.data.records
  })
}

// 点击树
const handleNodeClick = (e: any) => {
  state.queryForm.pkDept = e.id;
  getDataList()
};
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  // isPage: false,
  pageList: getUserList
})

//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state)
state.queryForm.month = formatDate(new Date(), 'YYYY-mm-dd')
// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}


// 导出excel
const exportExcel = () => {
  downBlobFile('/personnel/userClasses/export', Object.assign(state.queryForm, { ids: selectObjs }), 'userClasses.xlsx')
}

// 打开弹窗事件
const selectionChangDialog = (id, pkDept) => {

  // if (pkDept == null) {
  //   useMessage().error('请先选择左侧部门');
  //   return
  // }
  formDialogRef.value.openDialog(id, pkDept)
};
// 打开弹窗事件
const selectionMoreChangDialog = (userList) => {

  // const users = []
  // for (let i = 0; i < selectObjs.length; i++) {
  //   for (let index = 0; index < selectObjs[i].length; index++) {
  //     if (selectObjs[i].userClassVos[index].flag) {
  //       users.push(selectObjs[i].userClassVos[index])
  //     }
  //   }
  // }

  if (userList.length == 0) {
    useMessage().error('请先选择人员');
    return
  }
  formMoreDialogRef.value.openDialog(userList)
};
// 多选事件
const handleCurrentChange = (selections, row) => {
  if (selections.length == 0) {
    for (let index = 0; index < userList.value[row].userClassVos.length; index++) {
      userList.value[row].userClassVos[index].flag = false
    }
  } else {
    for (let index = 0; index < userList.value[row].userClassVos.length; index++) {
      userList.value[row].userClassVos[index].flag = false
      for (let i = 0; i < selections.length; i++) {
        if (userList.value[row].userClassVos[index].username === selections[i].username) {
          userList.value[row].userClassVos[index].flag = true
        }
      }
    }
  }
}

watch(state, (val, oldval) => {

  userList.value = []
  // let datas = state.dataList
  // userList.value.forEach(item => {
  //   console.log('item', item);
  //   const index = datas.findIndex((items: any) => items === item.username);
  //   if (index != -1) {
  //     multipleTableRef.value.toggleRowSelection(item)
  //   }
  //   // 
  // })

  // userList.value = state.dataList
  // for (let i = 0; i < userList.value.length; i++) {
  //   for (let index = 0; index < userList.value[i].userClassVos.length; index++) {
  //     // userList.value[i].userClassVos[index].join({ falg: false })
  //     Object.assign(userList.value[i].userClassVos[index], { falg: false })
  //     // userList.value[i].userClassVos[index].flag = false
  //   }
  // }
})

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ username }) => username);
  multiple.value = !objs.length;
  console.log('selectObjs', selectObjs);

  if (selectObjs.value.length == 0) {
    for (const key in state.dataList) {
      let num = state.dataList[key].username
      const index = userList.value.findIndex((items: any) => items.username === num);
      console.log('index空', index);
      if (index != -1) {
        userList.value.splice(index, 1)
      }
    }
  } else {
    for (const key in state.dataList) {
      let num = state.dataList[key].username
      const index = selectObjs.value.findIndex((items: any) => items === num);
      console.log('index', index);
      if (index != -1) {
        const index1 = userList.value.findIndex((items: any) => items.username === num);
        console.log('index111111111', index1);
        if (index1 == -1) {
          let data = state.dataList[key]
          userList.value.push(data)
        }
      } else {
        const index1 = userList.value.findIndex((items: any) => items.username === num);
        console.log('判断删除', index1);

        if (index1 != -1) {
          userList.value.splice(index1, 1)
        }
      }
    }
  }
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};
</script>